import router, { resetRouter } from "./index";
import asyncRoutes from "./asyncRoutes";
import defaultRoutes from "@/router/defaultRoutes";
import store from "../store";
import { filterRoutes, toAddRoute } from "@/utils/toAddRoutes";
// import "@/utils/getAsyncRoutes";

//路由前置守卫
//设置白名单
const whiteList = ["/login"];
// 路由跳转前，判断token
router.beforeEach(async (to, from, next) => {
  document.title = to.meta.name; // 设置页面title

  const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
  const role = userInfo?.userInfo;
  const token = userInfo?.token;
  if (token) {
    if (to.path == "/login") {
      next("/");
    } else {
      //判断是否请求了路由规则
      if (store.state.user.menuList.length === 0) {
        store.dispatch("getMenuList", role).then((accessRoutes) => {
          // 清空路由防止重复添加 或者清除之前添加的权限路由
          resetRouter();
          const arrList = filterRoutes(asyncRoutes, accessRoutes);
          defaultRoutes.forEach((item) => {
            if (item.name === "Layout") {
              item.children = item.children || []; // 确保children是一个数组
              item.children.push(...arrList); // 将asyncRoutes添加到children中
            }
          });
          defaultRoutes.push({
            path: "*",
            redirect: "/404",
            meta: {
              isMenu: false,
            },
          });
          router.addRoutes(defaultRoutes);
          // 根据roles权限生成可访问的路由表
          // arrList.forEach((item) => {
          //   router.addRoute("Layout", {
          //     path: item.path,
          //     name: item.name,
          //     meta: item.meta,
          //     component: item.component,
          //   });
          // });
          // toAddRoute(arrList);
          next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
        });
      } else {
        next();
      }
    }
  } else {
    // 无token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免费登录的白名单中，则直接进入
      next();
    } else {
      next(`/login?redirect=${to.path}`); // 其他页面无权限进入，则重定向到登录页面，login页面可获取redirect参数，便于登录后快速返回
    }
  }
});
